package org.linlinjava.litemall.wx.service;

import lombok.RequiredArgsConstructor;
import org.linlinjava.litemall.core.payment.PaymentResponseCode;
import org.linlinjava.litemall.core.payment.clover.service.UserCloverService;
import org.linlinjava.litemall.core.payment.clover.service.impl.GoodsCloverServiceImpl;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallOrder;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.OrderHandleOption;
import org.linlinjava.litemall.db.util.OrderStatusUtil;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;

import static org.linlinjava.litemall.wx.util.WxResponseCode.REFUND_ERROR_ID_CARD;

@Service
@RequiredArgsConstructor
public class WxCloverPayService {
    private final GoodsCloverServiceImpl goodsCloverService;
    private final UserCloverService userCloverService;
    private final LitemallOrderService orderService;

    public Object executePayment(String token,Integer userId, Integer orderId) {
        // 检测订单是否能够支付
        LitemallOrder order = orderService.findById(orderId);
        OrderHandleOption handleOption = OrderStatusUtil.build(order);
        if (!handleOption.isPay()) {
            return ResponseUtil.fail(PaymentResponseCode.ORDER_INVALID_OPERATION, "订单不能支付");
        }
        //执行支付
        try {
            return goodsCloverService.executePayment(token,userId, orderId);
        } catch (Exception e) {
            return ResponseUtil.fail(PaymentResponseCode.PAYMENT_FAIL, "支付失败");
        }
    }
    public ResponseUtil.Response rechargeBalance(Integer userId, BigDecimal amount, String token) {
        return userCloverService.executePayment(userId,amount,token);
    }








    public void presentPoint(Integer orderId) {
        goodsCloverService.presentPoint(orderId);
    }

    public void upgradeUserLevel(Integer orderId) {
        goodsCloverService.upgradeUserLevel(orderId);
    }

    public Object refund(Integer orderId) throws IOException{
       boolean res =  goodsCloverService.refund(orderId);

       if(!res){
           return ResponseUtil.fail(REFUND_ERROR_ID_CARD,"退款失败");
       }else{
           return ResponseUtil.ok("退款成功");
       }
    }



}
